<?php

require_once("libs/controller.php");
require_once("libs/images/SimpleImage.php");
require_once 'modelos/usuario.php';
require_once 'modelos/keys.php';
require_once 'modelos/ubicacion.php';
require_once 'modelos/info_paises.php';
require_once 'modelos/nombre_categoria.php';
require_once 'modelos/categorias_vendedor.php';
require_once 'modelos/versiones_tablas.php';
require_once 'modelos/foto.php';
require_once 'modelos/fotos_articulo.php';
require_once 'modelos/fotos_cotizacion.php';
require_once 'modelos/comentarios.php';


/**
 * Class with all common functions for everybody.
 * Every xMethod allways receives two aditional parameters:
 * - id        : User id who makes the request
 * - lang      : Lang of user device
 * - user_type : User type (V / C / G)
 *
 * @author Gonfre
 */
class CommonController extends Controller {
	
	protected $_IMAGE_THUMB_SIZE = 72;	
	protected $category_version = 0;
	
	public function __construct() {
	}
	
	
	public function index() {
	}
	
	
	/**
	 * Logins an user
	 * @param email
	 * @param password
	 */
	public function xLogin() {
		extract($_REQUEST);
		
		//Verificamos si el usuario y password existen
		$u = new Usuario();
		$u->addCondition("email", $email);
		$u->addCondition("password", "$password");
		if ($u->doSelectAll() && $u->next()) {
			
			//genero key
			$k = new Keys();
			$md5 = $k->generateKey($u->getId()); 
			if (!$md5) {
				$this->returnKO(-8, $lang);
			}
			
			//creo mensaje de respuesta
			$response = $this->createResponseHeader(1, $lang);
			$response = $response + array (
				"body" => array (
						"key" => $md5
				)
			);
			$this->putJsonResponse($response);
			
		} else {
			$this->returnKO(-4, $lang);
		}
		
	}
	
	
	/**
	 * Registers a seller
	 * @param name
	 * @param phone
	 * @param email
	 * @param password
	 * @param location
	 * @param categories
	 */
	public function xRegisterSeller() {
		extract($_REQUEST);
	
		$u = new Usuario();
		$u->getConnection()->iniciarTransaccion();
		
		//Email already exists?
		if ($u->doSelectAllWithCondition("email", $email) && $u->next()) {
			$this->returnKO(-9, $lang);
		}
		
		//New user
		$u->clear();
		$u->setValue("nombre", $name);
		$u->setValue("tipo", "V");
		$u->setValue("email", $email);
		$u->setValue("password", $password);
		$u->setValue("telefono", $phone);
		$u->setValue("id_ubicacion", $location);
		$u->setValue("tipo_cuenta", "N");
		$u->setValue("nro_local", $nro_local);
		
		if ($u->doSave()) {
			$response = $this->createResponseHeader(0, $lang);
				
			//Get the ID
			//if ($u->doSelectAllWithCondition("email", $email) && $u->next()) {
				$user_id = $u->getLastSavedId();
			//}
			
			//Insert Categories
			$cat = new Categorias_vendedor();
			$arr_c = explode(",", $categories);
			foreach ($arr_c as $category) {
				$cat->clear();
				$cat->setValue("id_vendedor", $user_id);
				$cat->setValue("id_categoria", $category);
				if (!$cat->doSave()) {
					$this->returnKO(-8, $lang, $u->getConnection());
				}
			}
			
			//genero key
			$k = new Keys();
			$md5 = $k->generateKey($user_id);
			if (!$md5) {
				$this->returnKO(-8, $lang, $u->getConnection());
			}
				
			$response = $response + array (
					"body" => array (
							"key" => $md5
					)
			);
			
			$u->getConnection()->confirmarTransaccion();
			$this->putJsonResponse($response);
		} else {
			$this->returnKO(-8, $lang);
		}
	}
	
	
	/**
	 * Registers a purchaser
	 * @param name
	 * @param phone
	 * @param email
	 * @param password
	 * @param country
	 */
	public function xRegistrerPurchaser() {
		extract($_REQUEST);
		
		$u = new Usuario();
		
		//Email already exists?
		if ($u->doSelectAllWithCondition("email", $email) && $u->next()) {
			$this->returnKO(-9, $lang);
		}
		
		//New user
		$u->clear();		
		$u->setValue("nombre", $name);
		$u->setValue("tipo", "C");
		$u->setValue("email", $email);
		$u->setValue("password", $password);
		$u->setValue("telefono", $phone);
		$u->setValue("id_ubicacion", $country);
		$u->setValue("tipo_cuenta", "N");
		
		if ($u->doSave()) {
			$response = $this->createResponseHeader(0, $lang);
			
			//Get the ID
			if ($u->doSelectAllWithCondition("email", $email) && $u->next()) {
				$user_id = $u->getId();
			}
			
			//genero key
			$k = new Keys();
			$md5 = $k->generateKey($user_id);
			if (!$md5) {
				$this->returnKO(-8, $lang);
			}
			
			$response = $response + array (
					"body" => array (
							"key" => $md5
					)
			);
			
			$this->putJsonResponse($response);
		} else {
			$this->returnKO(-8, $lang);
		}
		
	}

	
	/**
	 * Returns a product description list
	 * @param text 
	 */
	public function xGetDescriptionList() {
		extract($_REQUEST);
		
		
	}
	
	
	/**
	 * Returns a location list
	 * @param text
	 */
	public function xGetLocationList() {
		extract($_REQUEST);
		
		$u = new Ubicacion();
		if ($u->getLocationList($text)) {
			
			$response = $this->createResponseHeader(0, $lang);
			
			$list = array();
			while ($u->next()) {
				array_push($list, array(
					"id" => $u->getValue("id"),
					"text" => $u->getValue("path")
				));				
			}
			
			if (count($list) == 0) {
				$this->returnKO(2, $lang);
			}
			
			$response = $response + array (
					"body" => array (
							"list" => $list
					)
			);
			
			$this->putJsonResponse($response);
		} else {
			$this->returnKO(-8, $lang);
		}
	}
	
	
	/**
	 * Returns a category list
	 * @param text
	 */
	public function xGetCategoryList() {
		extract($_REQUEST);
		
		if ($this->category_version > 0) {
			$text = "*";
		}		
		
		$c = new Nombre_categoria();
		
		if ($c->getCategoryList($text, $lang)) {
			$response = $this->createResponseHeader(0, $lang);
			
			$list = array();
			while ($c->next()) {
				array_push($list, array(
				"id" => $c->getValue("id"),
				"name" => $c->getValue("nombre"),
				"icon" => $c->getValue("icono")
				));
					
			}
			
			if (count($list) == 0) {
				$this->returnKO(2, $lang);
			}
			
			if ($this->category_version == 0) {
			
				$response = $response + array (
						"body" => array (
								"category_list" => $list
						)
				);
			} else {
				$response = $response + array (
						"body" => array (
								"category_list" => $list,
								"version" => $this->category_version
						)
				);
			}
			
			$this->putJsonResponse($response);
		} else {
			$this->returnKO(-8, $lang);
		}
	}
	
	
	/**
	 * Returns available country list
	 */
	public function xGetCountryList() {
		extract($_REQUEST);
		
		$i = new Info_paises();
		if ($i->doSelectAllWithForeign("ubicacion", "id_pais")) {
			$response = $this->createResponseHeader(0, $lang);
				
			$list = array();
			while ($i->next()) {
				array_push($list, array(
				"id" => $i->getValue("id"),
				"name" => $i->getValue("ubicacion"),
				"money" => $i->getValue("moneda"),
				"symbol" => $i->getValue("simbolo"),
				"lang" => $i->getValue("idioma"),
				"mall_level" => $i->getValue("nivel_cc")
				));
			
			}
				
			if (count($list) == 0) {
				$this->returnKO(2, $lang);
			}
			
			$response = $response + array (
					"body" => array (
							"country_list" => $list
					)
			);
				
			$this->putJsonResponse($response);
		} else {
			$this->returnKO(-8, $lang);
		}
	}
	
	
	/**
	 * Adds a comment for a price
	 * @param id_price
	 * @param text
	 */
	public function xCommentPrice() {
		extract($_REQUEST);
		
		$c = new Comentarios();
		$c->setValue("id_cotizacion", $id_price);
		$c->setValue("texto", $text);
		$c->setValue("origen", $user_type);
		
		if ($c->doSave()) {
			$id_c = $c->getLastSavedId();
			
			$response = $this->createResponseHeader(0, $lang);
			$response = $response + array (
					"body" => array (
							"id_comment" => $id_c
					)
			);
				
			$this->putJsonResponse($response);
		} else {
			$this->returnKO(-8, $lang);
		}
	}

	
	/**
	 * Returns a location list by country and version
	 * @param country
	 */
	public function xGetLocationListByCountry() {
		extract($_REQUEST);

		//verifico si hay cambios en las ubicaciones
		$v = new Versiones_tablas();
		$v->addCondition("tabla", "UBICACION");
		$v->addCondition("id_pais", $country);
		if ($v->doSelectAll() && $v->next()) {
			$lu = $v->getValue("version");
			if ($last_update > 0 && $lu <= $last_update) {
				$this->returnKO(2, $lang);
			}
		} else {
			$this->returnKO(-8, $lang);
		}
		
		$u = new Ubicacion();
		if ($u->getLocationListByCountry($country)) {
				
			$response = $this->createResponseHeader(0, $lang);
				
			$list = array();
			while ($u->next()) {
				array_push($list, array(
				"id" => $u->getValue("id"),
				"text" => $u->getValue("path"),
				"level" => $u->getValue("nivel"),
				"parent" => $u->getValue("id_padre")
				));
	
			}
			
			if (count($list) == 0) {
				$this->returnKO(2, $lang);
			}
				
			$response = $response + array (
					"body" => array (
							"location_list" => $list,
							"version" => $lu
					)
			);
				
			$this->putJsonResponse($response);
		} else {
			$this->returnKO(-8, $lang);
		}
	}
	
	/**
	 * Returns a category list by version
	 * @param last_update
	 */
	public function xGetFullCategoryList() {
		extract($_REQUEST);

		//verifico si hay cambios en las ubicaciones
		$v = new Versiones_tablas();
		$v->addCondition("tabla", "CATEGORIA");
		if ($v->doSelectAll() && $v->next()) {
			$this->category_version = $v->getValue("version");
			if ($last_update > 0 && $this->category_version <= $last_update) {
				$this->returnKO(2, $lang);
			}
		} else {
			$this->returnKO(-8, $lang);
		}
		
		$this->xGetCategoryList();
	}
	

	/**
	 * Save photo file on BD
	 * @param $id_type
	 * @param $id_foreign
	 * @param $photo
	 * @param $name
	 * @param $type
	 */
	public function xPutPhoto() {
		extract($_REQUEST);

		$f = new Foto();
		$f->getConnection()->iniciarTransaccion();
		
		//get photo data bytes
		$data = $f->escapeBlob($photo);
		
		//$f->setBlobValue("foto", $data);
		$f->setValue("nombre", $name);
		$f->setValue("tipo", $type);
		
		if ($f->doSave()) {
			$id_photo = $f->getLastSavedId();
			
			$f = new Foto($id_photo);
			if (!$f->doUpdateBlob("foto", $data)) {
				$this->returnKO(-8, $lang, $f->getConnection());
			}
			
			//ID TYPE
			if (intval($id_type) == 8 || intval($id_type) == 13) { //Prices
				
				if (intval($id_type) == 8) { //Request Price
					$fAux = new Fotos_articulo();
					$fAux->setValue("id_articulo", $id_foreign);
				} else if (intval($id_type) == 13) { //Send Price
					$fAux = new Fotos_cotizacion();
					$fAux->setValue("id_cotizacion", $id_foreign);
				}
					
				//save
				$fAux->setValue("id_foto", $id_photo);
				if (!$fAux->doSave()) {
					$this->returnKO(-8, $lang, $f->getConnection());
				}
					
			} else if (intval($id_type) == 15 || intval($id_type) == 1) {
				
				if (intval($id_type) == 15) { //CommentPrice
					$fAux = new Comentarios($id_foreign);
				} else if (intval($id_type) == 1) { //users
					$fAux = new Usuario($id_foreign);
				}
				
				$fAux->setValue("id_foto", $id_photo);
				if (!$fAux->doUpdate()) {
					$this->returnKO(-8, $lang, $f->getConnection());
				}
				
			}
			
			// create response
			$response = $this->createResponseHeader(0, $lang);
			$response = $response + array (
					"body" => array (
							"id_photo" => $id_photo
					)
			);
			
			$f->getConnection()->confirmarTransaccion();
			
			//delete file
			unlink($photo);
			
			$this->putJsonResponse($response);
		} else {
			$this->returnKO(-8, $lang);
		}
	}
	
	/**
	 * Gets a photo file from DB
	 * @param $id_photo
	 */
	public function xGetPhoto() {
		extract($_REQUEST);
		
		$f = new Foto();
		$f->execQuery('SET bytea_output = "escape";');
		if ($f->doSelectOne($id_photo) && $f->next()) {
			$n = $f->getValue("nombre");
			$t = $f->getValue("tipo");
			$data = $f->getValue("foto");
			$path = "./tmp/$n";
			
			if ($data != null) {
									
				$image = $f->unescapeBlob($data);
				if (!$image) {
					$this->returnKO(-8, $lang);
				}
			} else {
				$this->returnKO(-7, $lang);
			}

			header("Content-type: $t");
			echo $image;
		} 
	}
	
	/**
	 * Gets a photo thumbnail from DB
	 * @param $id_photo
	 */
	public function xGetPhotoThumbnail() {
		extract($_REQUEST);
	
		$f = new Foto();
		$f->execQuery('SET bytea_output = "escape";');
		if ($f->doSelectOne($id_photo) && $f->next()) {
			$n = $f->getValue("nombre");
			$t = $f->getValue("tipo");
			$data = $f->getValue("foto");
			$path = "./tmp/$n";
				
			if ($data != null) {
					
				$image = $f->unescapeBlob($data);
				if (!$image) {
					$this->returnKO(-8, $lang);
				}
			} else {
				$this->returnKO(-7, $lang);
			}
	
			//Create photo from data
			$im = new SimpleImage();
			$im->fromString($image, $t);
			
			//resize
			if ($im->getWidth() >= $im->getheight()) {
				$im->resizeToWidth($this->_IMAGE_THUMB_SIZE);
			} else {
				$im->resizeToHeight($this->_IMAGE_THUMB_SIZE);
			}
			
			header("Content-type: $t");
			$im->echoImage();
			
		}
	}
}

?>